<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

abstract class Application{   
    protected static $instance;
    
    private $libs = array(
        "controller",
        "lib",
        "model"
    );
    
    private $lib;
    protected $dir;
    protected $layout; 
    
    private function includeLib($name){
        if(isset($this->lib[$name])){
            return true;
        }
        $return = false;
        foreach($this->libs as $lib){
            $path = $this->dir . '/' . $lib . '/' . $name . '.php';
            if(file_exists($path)){
                include_once($path);
                $this->lib[$name] = $path;
                $return = true;
            }
        }
        return $return;
    }
    
    protected function prepare(){
        spl_autoload_register(array($this, 'includeLib'));
        $name = $this->layout;
        $this->layout = new View();
        $this->layout->setFile($name);
        if(!$this->layout->isExists()){
            throw new Exception('Laout doesn\'t exists');
        }
    }
    
    protected function insertFolderToInclude($name){
        $this->libs[] = $name;
    }
    
    abstract protected function prepareLayout($actionString);
    
    public static function getInstance(){
        return self::$instance;
    }
    
    public function getMainApplicationDirectory(){
        return $this->dir;
    }
    
    public function run($controller, $action){
        $controller = $controller . 'Controller';
        if(class_exists($controller)){
            $obj = new $controller();
            $obj->executeAction($action);
            $this->prepareLayout($obj->getResult());
            echo $this->layout;
        }
    }
}

